<template>
  <div class="container">
    <div class="list-header">
      <DownIcon />
      下滑加载更多
      
    </div>
    <div class="list-content">
      <n-infinite-scroll style="height:1000px;padding: 10px; overflow: hidden;" :distance="10" @load="handleLoad">
        <div v-for="item in list" :key="item.id" class="list-item" @click="handleClick(item.id)">
          <div class="item-left">
            <div class="item-img">
              <img src="../assets/images/yzfc.png" />
            </div>
            <div class="item-content">
              <h3>{{ item.title }}</h3>
              <p class="item-content-text">{{ item.desc }}</p>
              <div class="item-tag">
                <n-tag size="small" style="border-radius: 10px; margin-right: 10px;"> <ChatIcon /> </n-tag>
                <n-tag size="small" style="border-radius: 10px;"> {{ item.category.title }} </n-tag>
              </div>
            </div>
          </div>
          <div class="item-right">
            <UpIcon />
          </div>
        </div>
      </n-infinite-scroll>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import ListIcon from './icons/ListIcon.vue';
import ChatIcon from './icons/ChatIcon.vue';
import UpIcon from './icons/UpIcon.vue';
import { useLinkStore } from '@/stores/linkStore';
import { getCategoryAPI } from '@/service/category/category';
import type { CategoryLink } from '@/service/category/type';
import { getLinksListApi } from '@/service/links/links';
import Swal from 'sweetalert2';
import DownIcon from './icons/DownIcon.vue';
import { debounce } from 'lodash';

const router = useRouter();
const route = useRoute();
const linkStore = useLinkStore();
const list = ref<CategoryLink[]>([]);

const loadData = async (id: string | undefined) => {
  try {
    if (id) {
      const res = await getCategoryAPI(Number(id));
      list.value = res.data;
      if (list.value.length === 0) {
        Swal.fire({
          title: '没有数据',
          icon: 'error',
        });
        await router.push('/');
      }
    } else {
      // 随机获取
      const randomPage = Math.floor(Math.random() * linkStore.totalPages) + 1;
      await linkStore.getLinksList(randomPage);
      list.value = linkStore.linkList as CategoryLink[];
    }
  } catch (error) {
    console.error("获取数据时出错:", error);
  }
};
// 初始化
onMounted(async () => {
  const id = Array.isArray(route.params.id) ? route.params.id[0] : route.params.id;
  loadData(id);
  
});
// 监听路由变化
watch(() => route.params.id, (newId) => {
  const id = Array.isArray(newId) ? newId[0] : newId;
  loadData(id);
});
// 点击跳转
const handleClick = (item: number) => {
  router.push(`/product/${item}`);
};
// 当前页数
const currentPage = ref(1);
// 是否正在加载
const isLoading = ref(false);
// 加载更多数据
const handleLoad = debounce(async () => {
  // 提示到底部上滑加载数据
  if (route.path === '/' && !isLoading.value) {
    isLoading.value = true;
    const maxPage = linkStore.totalPages;
    
    if (currentPage.value < maxPage) {
      currentPage.value++;
      try {
        const res = await getLinksListApi(currentPage.value);
        list.value = [...list.value, ...res.data.list as CategoryLink[]];
        // 提示下来加载更多
        Swal.fire({
         title: '下滑加载更多',
         icon: 'info',
         timer: 1000,
         timerProgressBar: true,
        });
      } catch (error) {
        console.error("加载更多数据时出错:", error);
      }
    }else {
      Swal.fire({
        title: '没有更多数据了',
        icon: 'error',
      });
    }
    
    isLoading.value = false;
  }
}, 300);
// 监听搜索
watch( () => linkStore.searchList,  (newList) => {
  list.value = newList as CategoryLink[];
  if (list.value.length === 0) {
    Swal.fire({
      title: '没有数据',
      icon: 'error',
    });
    // 等待1秒后跳转
    setTimeout(() => {
      window.location.reload();
    }, 1000);
  }
});

</script>

<style scoped lang="less">

.container {
  display: flex;
  flex-direction: column;
  width: 100%;
  align-items: center;
  justify-content: left;
  .list-header {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: left;
    padding: 10px;
    font-weight: bold;
    color: var(--color);
    position: relative;
   
  }
  .list-content {
    width: 100%;
    display: flex;
    flex-direction: wrap;
    align-items: center;
    justify-content: space-between;
    color: var(--color);
    .item-content-text {
      font-size: 12px;
    }
    .item-tag {
      margin-top: 10px;
      display: flex;
      align-items: center;
      justify-content: left;
    }
    .list-item {
      display: flex;
      height: auto;
      padding: 10px;
      background-color: #fff;
      margin-bottom: 3px;
      transition: all 0.3s ease;
      &:first-child {
        border-top-left-radius: 10px; // 左上圆角
        border-top-right-radius: 10px; // 右上圆角
      }
      .item-left {
        flex: 9;
        display: flex;
        align-items: center;
        justify-content: left;
        .item-img {
          width: 80px;
          height: 80px;
          margin-right: 10px;
          img {
            width: 100%;
            height: 100%;
          }
        }
      }
      .item-right {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid var(--color-border);
        border-radius: 10px;
      }
    }
  }
  .list-item:hover {
    background-color: #f0f0f0;
  }
}
@media (max-width: 768px) {
  .list-item {
    width:348px;
    flex-direction: column;
    .item-left, .item-right {
      width: 100%;
      justify-content: center;
    }
  }
}

</style>
